<template>
  <div class="bar-chart-container">
    <h3>{{ title }}</h3>
    <div ref="chart" class="bar-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    data: Array,
    title: String
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    initChart() {
      const chart = echarts.init(this.$refs.chart);
      const option = {
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.data.map(item => item.type)
        },
        yAxis: { type: 'value' },
        series: [{
          name: '数量',
          type: 'bar',
          data: this.data.map(item => item.value)
        }]
      };
      chart.setOption(option);
      this.chart = chart; // 保存 chart 实例
    },
    resizeChart() {
      this.chart?.resize(); // 窗口变化时调整图表大小
    }
  }
};
</script>

<style scoped>
.bar-chart-container {
  width: 100%;
  margin: 20px 0;
}
.bar-chart {
  width: 100%;
  height: 300px;
}
</style>